<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="汇总粒度" prop="particleSize">-->
<!--        <el-select v-model="queryParams.particleSize" placeholder="请选择汇总粒度" clearable>-->
<!--          <el-option-->
<!--            v-for="item in particleSizes"-->
<!--            :key="item.value"-->
<!--            :label="item.label"-->
<!--            :value="item.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="年月" prop="yearMouth">
        <el-input
          v-model="queryParams.yearMouth"
          placeholder="请输入年月"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker
          v-model="daterangeDataTime"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>


      <el-form-item label="合作媒体" prop="signatory">
<!--        <el-select v-model="queryParams.signatory" placeholder="请选择合作媒体" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.medium"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
        <el-input
          v-model="queryParams.signatory"
          placeholder="请输入合作媒体"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item v-if="roleCtr" label="供应商" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户简称" prop="customName">
        <el-input
          v-model="queryParams.customName"
          placeholder="请输入客户简称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务部门" prop="businessUnitName">
        <el-input
          v-model="queryParams.businessUnitName"
          placeholder="请输入业务部门"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售人员" prop="saleUser">
        <el-input
          v-model="queryParams.saleUser"
          placeholder="请输入销售人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="非赠款消耗" prop="noConsumption" label-width="120px">
        <el-select
          v-model="queryParams.noConsumption"
          placeholder="请选择非赠款消耗条件"
          clearable
        >
          <el-option
            label="非赠款消耗大于0"
            value="1"
          />
          <el-option
            label="非赠款消耗等于0"
            value="0"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-connection"
          size="mini"
          @click="secondary"
        >二次匹配转户</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dataMain:consumption:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row :gutter="12">
      <el-col :span="3">
        <div style="width: 300px;height: 100px;">
          <div style="text-align: center;line-height:50px;width: 100%;height: 50px;color: gray">
            总消耗
          </div>
          <div style="text-align: center;line-height:30px;width: 100%;height: 70px">
            {{totals.totalConsumption}}
          </div>
        </div>
      </el-col>
      <el-col :span="3">
        <div style="width: 300px;height: 100px;">
          <div style="text-align: center;line-height:50px;width: 100%;height: 50px;color: gray">
            赠款消耗
          </div>
          <div style="text-align: center;line-height:30px;width: 100%;height: 70px">
            {{totals.consumption}}
          </div>
        </div>
      </el-col>

      <el-col :span="3">
        <div style="width: 300px;height: 100px;">
          <div style="text-align: center;line-height:50px;width: 100%;height: 50px;color: gray">
            非赠款消耗
          </div>
          <div style="text-align: center;line-height:30px;width: 100%;height: 70px">
            {{totals.noConsumption}}
          </div>
        </div>
      </el-col>

    </el-row>
    <el-table v-loading="loading" :data="consumptionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="年月" align="center" prop="yearMouth" />
      <el-table-column label="日期" align="center" prop="dataTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dataTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="业务部门" align="center" prop="businessUnitName" />
      <el-table-column label="销售人员" align="center" prop="saleUser" />
      <el-table-column label="合作媒体" align="center" prop="signatory" />
      <el-table-column label="客户简称" align="center" prop="customName" />
      <el-table-column  v-if="roleCtr" label="供应商" align="center" prop="supplierName" />
      <el-table-column label="总消耗" align="center" prop="totalConsumption" />
      <el-table-column label="非赠款消耗" align="center" prop="noConsumption"  width="100"/>
      <el-table-column label="赠款消耗" align="center" prop="consumption" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dataMain:consumption:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dataMain:consumption:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改消耗总表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="年月" prop="yearMouth">
          <el-input v-model="form.yearMouth" placeholder="请输入年月" />
        </el-form-item>
        <el-form-item label="日期" prop="dataTime">
          <el-date-picker clearable
            v-model="form.dataTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="帐户ID" prop="accountId">
          <el-input v-model="form.accountId" placeholder="请输入帐户ID" />
        </el-form-item>
        <el-form-item label="帐户名称" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入帐户名称" />
        </el-form-item>
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="总消耗" prop="totalConsumption">
          <el-input v-model="form.totalConsumption" placeholder="请输入总消耗" />
        </el-form-item>
        <el-form-item label="非赠款消耗" prop="noConsumption">
          <el-input v-model="form.noConsumption" placeholder="请输入非赠款消耗" />
        </el-form-item>
        <el-form-item label="赠款消耗" prop="consumption">
          <el-input v-model="form.consumption" placeholder="请输入赠款消耗" />
        </el-form-item>
        <el-form-item label="合作媒体" prop="signatory">
          <el-input v-model="form.signatory" placeholder="请输入合作媒体" />
        </el-form-item>
        <el-form-item label="供应商id" prop="supplierId">
          <el-input v-model="form.supplierId" placeholder="请输入供应商id" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="客户ID" prop="customId">
          <el-input v-model="form.customId" placeholder="请输入客户ID" />
        </el-form-item>
        <el-form-item label="客户简称" prop="customName">
          <el-input v-model="form.customName" placeholder="请输入客户简称" />
        </el-form-item>
        <el-form-item label="业务部门" prop="businessUnitName">
          <el-input v-model="form.businessUnitName" placeholder="请输入业务部门" />
        </el-form-item>
        <el-form-item label="销售人员" prop="saleUser">
          <el-input v-model="form.saleUser" placeholder="请输入销售人员" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".zip"
        name="file"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">

          <span>仅允许导入zip格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConsumption, getConsumption, delConsumption, addConsumption, updateConsumption,secondary } from "@/api/dataMain/consumption";
import {getToken} from "@/utils/auth";
export default {
  name: "Consumption",
  dicts: ['medium'],
  data() {
    return {
      roleCtr:false,
      totals:{},
      particleSizes:[
        {
          label:'日粒度',
          value:'日粒度'
        },
        {
          label:'月粒度',
          value:'月粒度'
        },
        {
          label:'年粒度',
          value:'年粒度'
        }
      ],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消耗总表表格数据
      consumptionList: [],
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/dataMain/consumption/uploadFile"
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeDataTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        particleSize: undefined,
        yearMouth: undefined,
        dataTime: undefined,
        accountId: undefined,
        accountName: undefined,
        companyName: undefined,
        signatory: undefined,
        supplierName: undefined,
        customName: undefined,
        businessUnitName: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    const username = this.$store.state.user
    if(username.roles !== undefined && username.roles.length>0){
      username.roles.forEach(role => {
        if(role == 'admin' || role == 'ptadmin'){
            this.roleCtr = true
        }
      })
    }
  },
  methods: {
    secondary(){
      secondary().then(res=>{

      })
    },
    /** 查询消耗总表列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDataTime && '' != this.daterangeDataTime) {
        this.queryParams.params["beginDataTime"] = this.daterangeDataTime[0];
        this.queryParams.params["endDataTime"] = this.daterangeDataTime[1];
      }
      listConsumption(this.queryParams).then(response => {
        this.consumptionList = response.rows;
        this.total = response.total;
        if(response.totals == null){
          this.totals = {
            totalConsumption:0,
            noConsumption:0,
            consumption:0,
          }
        }else{
          this.totals = response.totals;
        }

        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        yearMouth: undefined,
        dataTime: undefined,
        accountId: undefined,
        accountName: undefined,
        companyName: undefined,
        totalConsumption: undefined,
        noConsumption: undefined,
        consumption: undefined,
        signatory: undefined,
        supplierId: undefined,
        supplierName: undefined,
        customId: undefined,
        customName: undefined,
        businessUnit: undefined,
        businessUnitName: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateTime: undefined,
        updateBy: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDataTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加消耗总表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      console.log(row)
      const id = row.id || this.ids
      getConsumption(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改消耗总表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateConsumption(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addConsumption(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除消耗总表编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delConsumption(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dataMain/consumption/export', {
        ...this.queryParams
      }, `consumption_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('dataMain/consumption/importTemplate', {
      }, `consumption_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
